package com.jianguozh.difs.framework.validator;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.IEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 枚举参数校验实现
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/29 11:16
 */
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    // 枚举校验注解
    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {

        boolean  ignoreEmpty = annotation.ignoreEmpty();
        if(ignoreEmpty && ObjectUtil.isNull(value) && ignoreEmpty){
            return true;
        }else if(!ignoreEmpty && ObjectUtil.isNull(value) ){
            return false;
        }

        boolean result = false;
        Class<?> cls = value.getClass();
        // target为枚举，并且value有值，或者不忽视空值，才进行校验
        if (cls.isEnum() && null != value || !ignoreEmpty) {
            IEnum[] enums = (IEnum[]) cls.getEnumConstants();
            for (IEnum obj : enums) {
                if (obj.equals(value)) {
                    result = true;
                    break;
                }
            }
        } else {
            result = true;
        }
        return result;
    }
}
